package com.zjq.smartdevice.websocket.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.HashMultimap;
import com.zjq.smartdevice.events.HumitureCheckEvent;
import com.zjq.smartdevice.events.PowerCommandEvent;
import com.zjq.smartdevice.pojo.SysHumiture;
import com.zjq.smartdevice.service.SysHumitureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

/**
 * @User zhangjiaqi
 * @Project project
 * @Package com.zjq.smartdevice.websocket.handler
 * @Date 2022/3/27 21:22
 */

@Component
public class HumitureCommandHandler extends BaseCommandHandler {


    HashMultimap<String,Double> hashMultimap = HashMultimap.create();//创建一个value是集合的map

    private SysHumitureService service;

    @Autowired
    public void setService(SysHumitureService service) {

        this.service = service;
    }

    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    //收到数据要单独处理


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        CompletableFuture.runAsync(() -> {
            try {
                super.handleTextMessage(session, message);
                System.err.println("单独处理温湿度数据");
                String deviceKey = (String) session.getAttributes().get("deviceKey");
                String payload = message.getPayload();//数据,是一个json格式的数据{"humidity":18.00,"temperature":82.40}
                Map map = objectMapper.readValue(payload, Map.class);//包含humidity,temperature两个key
                SysHumiture sysHumiture = new SysHumiture();
                sysHumiture.setDeviceId(deviceKey);
                sysHumiture.setUploadTime(new Date());
                sysHumiture.setHumidity((Double) map.get("humidity"));
                double temperature = (double) map.get("temperature");//w温度,是华氏温度
                double sheshi = (temperature - 32) / 1.8;//转成摄氏温度
                sysHumiture.setTemperature(sheshi);
                service.addSysHumiture(sysHumiture);
                //我想拿最近一段时间的数据进行判断,如果平均值高于某个阈值我就触发什么情况,低于什么值就触发什么情况
                //比如我现在想简单的在定义一个功能,温度高于28°打开一个指定的设备,低于28°关闭设备
                hashMultimap.put(deviceKey, sheshi);//保存当前的温度
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    @EventListener
    public void onEvent(HumitureCheckEvent event) {
        System.err.println("计算温湿度平均值的任务开始了");
        //获取最近一个循环周期内的温度的平均值,然后进行计算,超出某个值就做一些事情
        //最近的数据保存在什么地方,比如我们可以保存在一个map中,在这里从map中获取出来,然后计算平均值
        Set<String> keySet = hashMultimap.keySet();//拿到所有的key
        for (String key : keySet) {//key就是每一个温湿度传感的id
            Set<Double> doubles = hashMultimap.removeAll(key);//获取并移除map中指定的数据,因为数据本次使用之后就没用了
            // double sum = doubles.stream().mapToDouble(Double::doubleValue).sum();//遍历求所有数据的和
            //  double avg = sum / doubles.size();
            //orelse就是如果不能得到结果就是用orelse 就相当于 if else中的else
            double avg = doubles.stream().mapToDouble(Double::doubleValue).average().orElse(0d);

            if (avg >= 28) {
                //开风扇
                System.err.println("开风扇");
                getContext().publishEvent(new PowerCommandEvent("1234567890", "0"));
            }else{
                //关风扇
                System.err.println("关风扇");
                getContext().publishEvent(new PowerCommandEvent("1234567890", "1"));
            }
        }
    }
}
